<?php

require_once dirname(__FILE__) . '/../lib/scratch_cardGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/scratch_cardGeneratorHelper.class.php';

/**
 * scratch_card actions.
 *
 * @package    Amman to London
 * @subpackage scratch_card
 * @author     Adel Abu-Saif <adeljas@msn.com>
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class scratch_cardActions extends autoScratch_cardActions {

    protected function processForm(sfWebRequest $request, sfForm $form) {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid()) {
            $notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';

            try {
                $info = $form->save();
            } catch (Doctrine_Validator_Exception $e) {

                $errorStack = $form->getObject()->getErrorStack();

                $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " with validation errors: ";
                foreach ($errorStack as $field => $errors) {
                    $message .= "$field (" . implode(", ", $errors) . "), ";
                }
                $message = trim($message, ', ');

                $this->getUser()->setFlash('error', $message);
                return sfView::SUCCESS;
            }

            $number_of_cards = $info[0];
            $value = $info[1];
            $first_id = $info[2];
            sfContext::getInstance()->getConfiguration()->loadHelpers(array('Url'));
            $link = url_for('scratch_card/generate_csv?fid=' . $first_id);
            $here = "<a href=\"$link\">here</a>";
            $card_text = $number_of_cards == 1 ? 'card' : 'cards';
            $this->getUser()->setFlash('notice', "Successfully generated $number_of_cards \"$value JOD\" $card_text. click [ $here ] to export.");
            $this->redirect('scratch_card/index');
        } else {
            $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
        }
    }

    public function executeGenerate_csv($request) {
        $first_id = $request->getParameter('fid', 0);
        $arr = ScratchCardTable::getInstance()->createQuery()->where('id >= ?', $first_id)->fetchArray();
        $csv = $this->array_to_csv($arr);

        $file_name = 'cards_' . date('Y_m_d');
        header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=$file_name.csv");
        header("Pragma: no-cache");
        header("Expires: 0");

        die($csv);
    }

    private function array_to_csv($array = array()) {
        $out_str = 'serial number, card number, value, created at, valid until';
        $out_str.="\r\n";
        if (count($array)) {
            foreach ($array as $k => $one) {
                $ctime = strtotime($one['created_at']);
                $created_at = date('Y-m-d', $ctime);
                // @fixme : not all months have 30 days !!
                $valid_until = $ctime += 60 * 60 * 24 * 30 * 6;
                $valid_until_str = date('Y-m-d', $valid_until);
                $out_str.="{$one['id']},\"=\"\"{$one['card_number']}\"\"\",{$one['value']},\"{$created_at}\",\"{$valid_until_str}\"";
                $out_str.="\r\n";
            }
        }
        return $out_str;
    }

}
